package com.godofgamblers.hotelmanagementsystem.handler;

import com.godofgamblers.hotelmanagementsystem.pojo.*;
import com.godofgamblers.hotelmanagementsystem.service.RoomService;
import com.godofgamblers.hotelmanagementsystem.service.*;
import com.godofgamblers.hotelmanagementsystem.util.PropertiesUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: 伴你时光尽头
 * @Date: 2019/10/12 14:41
 */
@Data
@Controller
@RequestMapping("/systemsetting")
public class SystemSettingHandler {
    @Autowired
    private User_LevelService user_levelService;//自动装配
    @Autowired
    private Room_TypeService room_typeService;//自动装配
    @Autowired
    private Discount_StoreService discount_storeService;//自动装配
    @Autowired
    private RoomService roomService;//自动装配
    @Autowired
    private UserService userService;//自动装配
    @Autowired
    private RoleService roleService;//自动装配

    private ModelAndView modelAndView = new ModelAndView();//创建ModelAndView对象
    private List<User_Level> user_levels;//创建user_level对象集合
    private List<Room_Type> room_types;//创建Room_Type对象集合
    private List<Room> rooms;//创建Room对象集合
    private List<User> users;//创建user对象集合
    private List<Role> roles;//创建role对象集合
    public static boolean all_discount = false;//全场打折标志  false为不打折   true为打折  需友方配合
    public static boolean round_flag = false;//结账取整标志  false为不取整   true为取整  需友方配合
    public static int cleanTime=15*60*1000;//打扫时间  默认15分钟

    private String username;
    private String password;
    private String databaseip;
    private String databaseport;
    private String filePath;
    private String dbName;

    //showall   取出各个子页面需要的数据集合addproject到modelandview并返回 以便前端页面取


    /**
     * 请求URL为：/user_level/showall
     * 查询所有的数据库user_level中所有的数据，返回集合，并通过modelandview发送给前端
     *
     * @return modelAndView
     */
    @RequestMapping(value = "/user_level/showall"/*,produces="text/html;charset=utf-8"*/)
//    @ResponseBody()
    public ModelAndView showAllItem(String flagValue) {

        Properties properties = PropertiesUtil.getProperties();
        username = (String)properties.get("username");
        password = (String)properties.get("password");
        databaseip = (String)properties.get("databaseip");
        databaseport = (String)properties.get("databaseport");
        filePath = (String)properties.get("filePath");
        dbName = (String)properties.get("dbName");

        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        room_types = room_typeService.showAllItem();//调用方法获取room_type数据库中所有数据并封装成room_type类型集合

        rooms = roomService.showAllItem();//调用方法获取room数据库中所有数据并封装成room类型集合
        for (Room room : rooms) {
            if (room.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                room.setState("空闲中");
            } else if (room.getRoom_state() == 1) {
                room.setState("已入住");
            } else if (room.getRoom_state() == 2) {
                room.setState("故障中");
            } else if (room.getRoom_state() == 3) {
                room.setState("打扫中");
            }
        }

        users = userService.showAllItem();
        roles = roleService.showAllItem();
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("room_types", room_types);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("rooms", rooms);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("users", users);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("roles", roles);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        if(flagValue!=null){
            modelAndView.addObject("flagValue",flagValue);
        }
        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
//        System.out.println(room_types);
//        System.out.println("showall");
        return modelAndView;
    }


    //user_level


    /**
     * 请求URL为：/user_level/delete
     * 根据level_id删除数据库user_level中对应的数据项
     *
     * @param level_id 前端获取到并传入
     * @return 格式 不可为void
     */
    @RequestMapping(value = "/user_level/delete"/*,produces="text/html;charset=utf-8"*/)
    public ModelAndView deleteOneItem(Integer level_id) {
//        System.out.println(level_id);
        user_levelService.deleteItemById(level_id);//调用方法根据level_id删除数据库中对应id项
//        System.out.println("delete");
        return null;
    }

    /**
     * 请求URL为：/user_level/update
     * 根据传入对象user_level修改数据库user_level中对应的数据项
     *
     * @param user_level User_Level PoJo类
     * @return
     */
    @RequestMapping("/user_level/update")
    public ModelAndView changeItem(User_Level user_level,String flagValue) {
//        System.out.println(user_level);
//        System.out.println("update");
        user_levelService.updateItem(user_level);//调用方法，修改数据库中指定项数据
        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示

        modelAndView.addObject("flagValue",flagValue);

        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
        return modelAndView;
    }


    /**
     * 请求URL为：/user_level/update
     * 根据传入对象user_level插入新的数据到数据库user_level中
     *
     * @param user_level User_Level PoJo类
     * @return
     */
    @RequestMapping("/user_level/additem")
    public ModelAndView additem(User_Level user_level ,String flagValue) {
//        System.out.println(user_level);
//        System.out.println("additem");
        user_levelService.insertItem(user_level);//调用方法，向数据库中插入新的数据
        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("flagValue",flagValue);
        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
        return modelAndView;
    }


    //room_type


    @RequestMapping("/room_type/update")
    public ModelAndView changeItem(Room_Type room_type) {
//        all_discount = !all_discount;
        allTypeDiscount(null, null);
        allTypeDiscount(all_discount, null);
        room_typeService.changeOneItem_Discount(room_type);//调用方法，修改数据库中指定项数据

        return null;
    }

    @RequestMapping("/room_type/roundmoney")
    @ResponseBody
    public String changRoundFlag(Boolean round_flag1) {
        if (round_flag1 == null) {
            if (round_flag) {
                return "取整状态";
            } else {
                return "非取整状态";
            }
        }
        round_flag = round_flag1;
        if (round_flag) {
            return "取整状态";
        } else {
            return "非取整状态";
        }
    }

    @RequestMapping("/room_type/discountall")
    @ResponseBody
    public String allTypeDiscount(Boolean all_discount1, BigDecimal room_type_discount) {

        if (all_discount1 == null && room_type_discount == null) {
            all_discount = false;
            return "非全场状态";
        }
        all_discount = all_discount1;
        if (all_discount1) {
            //调用方法，修改数据库中指定项数据
            List<Room_Type> room_types = room_typeService.showAllItem();

            Discount_Store discount_store = new Discount_Store();
            if (room_types != null) {
                for (Room_Type room_type : room_types) {
                    discount_store.setDiscount_store_discount(room_type.getRoom_type_discount());
                    discount_store.setRoom_type_id(room_type.getRoom_type_id());
                    discount_storeService.insertItem(discount_store);
                }
                room_typeService.changeAllItem_Discount(room_type_discount);
            }
            return "全场状态";
        } else {
            Room_Type room_type = new Room_Type();
            List<Discount_Store> discount_stores = discount_storeService.showAllItem();
            if (discount_stores != null) {
                for (Discount_Store discount_store : discount_stores) {
                    room_type.setRoom_type_discount(discount_store.getDiscount_store_discount());
                    room_type.setRoom_type_id(discount_store.getDiscount_store_id());
                    room_typeService.changeOneItem(room_type);
                }
                discount_storeService.deleteAllItem();
            }
            return "非全场状态";
        }
    }


    //room


    @RequestMapping("/room/delete")
    @ResponseBody
    public String deleteRoom(Room room) {
//        System.out.println(room);
        roomService.deleteItem(room);
        room_typeService.reduceStockById(room);
        return "";
    }

    @RequestMapping("/room/changeitem")
    public ModelAndView changeItem(Room room) {
        System.out.println("*****************************************************************" + room);
        //根据id查找对应的room用于比较 功能见下
        Room room1 = roomService.showItemById(room);

        //对房间状态进行处理
        if (!room1.getRoom_state().equals(room.getRoom_state())) {//判断此次请求是否修改房间状态
            if (room1.getRoom_state() == 0 || room1.getRoom_state() == 1) {//当房间状态为0/1时 且更改为2/3时 库存需要进行修改
                if (room.getRoom_state() == 2 || room.getRoom_state() == 3) {//判断请求目标房间状态是否为 故障 和 打扫 如果是  则需要对房间类型对应库存进行修改
                    roomService.changeState(room);
                    room_typeService.reduceStockById(room);
                } else {//如果是0/1之间互相切换则不需要修改库存
                    roomService.changeState(room);
                }
            } else {//如果房间状态为2/3 且更改为0/1时，库存需要修改
                if (room.getRoom_state() == 0 || room.getRoom_state() == 1) {
                    roomService.changeState(room);
                    room_typeService.addStockById(room);
                } else {//如果是2/3之间互相切换则不需要修改库存
                    roomService.changeState(room);
                }
            }
        }

        //对房间类型进行处理
        //首先判断目标修改类型和当前类型是否相同
        if (!room1.getRoom_type_id().equals(room.getRoom_type_id())) {//如果不相同才进行操作
            System.out.println("9999999999999999999999999999999999999*******************************修改房间类型");
            //首先将目标类型的库存增加
            room_typeService.addStockById(room);
            //再将当前类型的库存减少
            room_typeService.reduceStockById(room1);
            //再进行修改
            roomService.changeType(room);
        }

        return showAllItem("searchroom");
    }

    @RequestMapping("/room/addroom")
    @ResponseBody
    public String addRoom(Room room) {
        Room room1 = roomService.showItemByNum(room);
        if (room1 != null) {//判断软删除状态为1的数据 即存在状态的   如果能够查到数据 则表示该房间存在
            return "房间号已存在，新增失败";
        }
        Room room2 = roomService.showItemByNumIgnoreFlag(room);
        if (room2 != null) {//查询软删除状态为0的数据  即软删除状态的数据     如果能够查到数据  则采用update方式体现新增房间操作
            roomService.insertItemByUpdate(room);
            room_typeService.addStockById(room);
            return "新增房间" + room.getRoom_num() + "成功";
        } else {//如果 不 能查到数据  则采用insert方式体现新增房间操作
            roomService.insertItem(room);
            room_typeService.addStockById(room);
            return "新增房间" + room.getRoom_num() + "成功";
        }
    }

    @RequestMapping("/room/searchroom")
    public ModelAndView searchRoom(Room room,String flagValue) {//根据房间号查询以及根据类型查询
//        System.out.println("***************************************************************************" + room);
        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        room_types = room_typeService.showAllItem();//调用方法获取room_type数据库中所有数据并封装成room_type类型集合
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("room_types", room_types);//向modelandview中添加数据，前端thymeleaf遍历获取显示

        if (room.getRoom_type_id() != null) {//如果房间类型id不为null则说明一定至少是根据房间类型查询
            if (room.getRoom_num() == "") {//房间类型不为null'的前提下  房间编号为null则表示值根据房间类型查询
                rooms.clear();
                rooms = roomService.showItemsByType(room);//查询所有指定房间类型的room 返回room集合
                for (Room room1 : rooms) {
                    if (room1.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                        room1.setState("空闲中");
                    } else if (room1.getRoom_state() == 1) {
                        room1.setState("已入住");
                    } else if (room1.getRoom_state() == 2) {
                        room1.setState("故障中");
                    } else if (room1.getRoom_state() == 3) {
                        room1.setState("打扫中");
                    }
                }
                modelAndView.addObject("rooms", rooms);//向modelandview中添加数据，前端thymeleaf遍历获取显示
            } else {//房间编号不为null则表示要同时满足房间编号以及房间类型
                rooms.clear();
                rooms = roomService.showItemsByTypeAndNum(room);//查询所有指定房间类型以及num的room 返回room集合
                for (Room room1 : rooms) {
                    if (room1.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                        room1.setState("空闲中");
                    } else if (room1.getRoom_state() == 1) {
                        room1.setState("已入住");
                    } else if (room1.getRoom_state() == 2) {
                        room1.setState("故障中");
                    } else if (room1.getRoom_state() == 3) {
                        room1.setState("打扫中");
                    }
                }
                modelAndView.addObject("rooms", rooms);//向modelandview中添加数据，前端thymeleaf遍历获取显示
            }
        }
        if (room.getRoom_type_id() == null) {//如果房间类型id为null 则说明一定是根据房间num查询
            rooms.clear();
            rooms.add(roomService.showItemByNum(room));
            for (Room room1 : rooms) {
                if (room1.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                    room1.setState("空闲中");
                } else if (room1.getRoom_state() == 1) {
                    room1.setState("已入住");
                } else if (room1.getRoom_state() == 2) {
                    room1.setState("故障中");
                } else if (room1.getRoom_state() == 3) {
                    room1.setState("打扫中");
                }
            }
            modelAndView.addObject("rooms", rooms);
        }
        modelAndView.addObject("flagValue",flagValue);
        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
        return modelAndView;
    }


    //数据库备份
    @RequestMapping("/databasebackup")
    @ResponseBody
    public String databasebackup() throws Exception {
//        String filePath = "D:\\";
//        System.out.println("?????????????????????????????????????????????????????????????????");



//        System.out.println("999999999999999999999cc********username"+username);
//        System.out.println("999999999999999999999cc********password"+password);
//        System.out.println("999999999999999999999cc********databaseip"+databaseip);
//        System.out.println("999999999999999999999cc********databaseport"+databaseport);
//        System.out.println("999999999999999999999cc********filePath"+filePath);

        /*String fileName="批量上传模板.xlsx";*/
//        String dbName = "hms_test";
        try {
            Process process = Runtime.getRuntime().exec(
                    "cmd  /c  mysqldump -h"+databaseip+" -P"+databaseport+" -u "+username+" -p"+password+" " + dbName + " > "
                            + filePath + "/" + dbName + ".sql");
            //备份的数据库名字为hms_test，数据库连接和密码为root 123123
            System.out.println("success!!!");
            return "success";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }
    }


    //数据库恢复
    @RequestMapping("/databaserecover")
    @ResponseBody
    public String databaserecover() throws Exception {
//        String filePath = "D:\\";
//        System.out.println("?????????????????????????????????????????????????????????????????");


        /*String fileName="批量上传模板.xlsx";*/
//        String dbName = "hms_test";
        try {
            Process process = Runtime.getRuntime().exec(
                    // mysql -h39.105.17.213 -P3306 -uroot -p123123 "+dbName+"< "+filePath+dbName+".sql  //将D备份的数据库脚本，恢复到数据库中
                    "cmd  /c  mysql -h"+databaseip+" -P"+databaseport+" -u"+username+" -p"+password+" "+ dbName + "< " + filePath + dbName + ".sql");
            //备份的数据库名字为hms_test，数据库连接和密码为root 123123
            System.out.println("success!!!");
            return "success";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }
    }


    //操作员设置

    @RequestMapping("/user_role/change")
    public ModelAndView changeRole(User user) {//修改角色
        System.out.println(user);
        roleService.changeRole(user);//根据user_id和role_id修改在user_role表中的对应关系，
        return showAllItem("searchuser");
    }

    @RequestMapping("/user_role/delete")
    @ResponseBody
    public String delteRole(User user) {//删除操作员   即将其角色改为用户
        System.out.println(user);
        roleService.deleteRole(user);//根据user_id和role_id修改在user_role表中的对应关系，
        return null;
    }

    @RequestMapping("/user_role/searchuser")
    public ModelAndView searchUser(User user,String flagValue) {
        System.out.println(user);
        users.clear();
        user=userService.searchUser(user);
        if(user!=null){
            users.add(user); //根据手机号查训用户
            modelAndView.addObject("users", users);
        }

        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        room_types = room_typeService.showAllItem();//调用方法获取room_type数据库中所有数据并封装成room_type类型集合

        rooms = roomService.showAllItem();//调用方法获取room数据库中所有数据并封装成room类型集合
        for (Room room : rooms) {
            if (room.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                room.setState("空闲中");
            } else if (room.getRoom_state() == 1) {
                room.setState("已入住");
            } else if (room.getRoom_state() == 2) {
                room.setState("故障中");
            } else if (room.getRoom_state() == 3) {
                room.setState("打扫中");
            }
        }


        roles = roleService.showAllItem();
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("room_types", room_types);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("rooms", rooms);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("roles", roles);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("flagValue",flagValue);
        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
//        System.out.println(room_types);
//        System.out.println("showall");
        return modelAndView;
    }

    @RequestMapping("/user_role/searchuserbyaccount")
    public ModelAndView searchUserByAccount(User user,String flagValue) {
//        System.out.println(user);
        users.clear();
        user=userService.searchUserByAccount(user);
        if(user!=null){
            users.add(user); //根据手机号查训用户
            modelAndView.addObject("users", users);
        }


        user_levels = user_levelService.showAllItem();//调用方法获取user_level数据库中所有数据并封装成user_level类型集合
        room_types = room_typeService.showAllItem();//调用方法获取room_type数据库中所有数据并封装成room_type类型集合

        rooms = roomService.showAllItem();//调用方法获取room数据库中所有数据并封装成room类型集合
        for (Room room : rooms) {
            if (room.getRoom_state() == 0) {//房间状态 0=空闲  1=入住 2=故障 3=打扫
                room.setState("空闲中");
            } else if (room.getRoom_state() == 1) {
                room.setState("已入住");
            } else if (room.getRoom_state() == 2) {
                room.setState("故障中");
            } else if (room.getRoom_state() == 3) {
                room.setState("打扫中");
            }
        }


        roles = roleService.showAllItem();
        modelAndView.addObject("user_levels", user_levels);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("room_types", room_types);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("rooms", rooms);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("roles", roles);//向modelandview中添加数据，前端thymeleaf遍历获取显示
        modelAndView.addObject("flagValue",flagValue);
        modelAndView.setViewName("back_setting.html");//指定视图名称，跳转到指定页面
//        System.out.println(room_types);
//        System.out.println("showall");
        return modelAndView;
    }

    @RequestMapping("/room/timechangestate")
    public ModelAndView timeChangeState(Room room) {
        //设定定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                room.setRoom_state(0);
                if(roomService.showItemByNum(room).getRoom_state()==3){
                    roomService.changeStateByNum(room);
                }
            }

        }, cleanTime);
        return null;
    }


    @RequestMapping("/cleantime")
    @ResponseBody
    public String  changeCleanTime(Integer cleantime){
        if(cleantime==null){
            cleantime=(cleanTime/1000/60);
//            System.out.println("??"+cleantime);
            return cleantime.toString();
        }else{
            cleanTime=cleantime*60*1000;
            System.out.println(cleanTime);
            return "修改成功";
        }
    }
}
